package com.example.student1.webapi;


import com.example.student1.domain.Student;
import com.example.student1.domain.Student_Login;
import com.example.student1.domain.Teacher_Login;
import com.example.student1.service.StudentService;
import com.example.student1.service.Student_LoginService;
import com.example.student1.service.Teacher_LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/login")
public class LoginRestController {
    /*@Autowired
    StudentService studentService;*/
    @Autowired
    Student_LoginService student_LoginService;
    @Autowired
    Teacher_LoginService teacher_LoginService;

    @GetMapping("/user")
    public int user(HttpServletRequest httprequest, String username, String password){
        List<Student_Login> students = student_LoginService.findByNameAndPassword(username,password);
        List<Teacher_Login> teachers = teacher_LoginService.findByNameAndPassword(username,password);
        if (students.size()>0)
        {
            HttpSession session = httprequest.getSession();
            session.setAttribute("userid",students.get(0).getId());
            session.setAttribute("user",students.get(0));
            session.setAttribute("username",username);
            return 1;
        }
        else if (teachers.size()>0){
            HttpSession session = httprequest.getSession();
            session.setAttribute("userid",teachers.get(0).getId());
            session.setAttribute("user",teachers.get(0));
            session.setAttribute("username",username);
            return 2;
        }
        else
        {
            return -1;
        }
    }
}
